package com.jz.digital.caigou_shpiuliao

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.jz.digital.R
import com.jz.digital.base.BaseClickActivity
import com.jz.digital.bean.ServerBean
import com.jz.digital.dialog.DialogUtil
import com.jz.digital.scan.ScanCodeActivity
import com.jz.digital.utils.DataUtil
import com.jz.digital.utils.systembar.ImmersionBar
import com.jz.digital.view.CommonRecyclerViewAdapter
import com.jz.digital.view.CommonRecyclerViewHolder
import com.yanzhenjie.recyclerview.SwipeMenuItem
import kotlinx.android.synthetic.main.activity_caigou_shouliao_layout.recycler
import kotlinx.android.synthetic.main.activity_caigou_shouliao_layout.tv_commit
import kotlinx.android.synthetic.main.activity_caigou_shouliao_layout.tv_scan_content
import kotlinx.android.synthetic.main.layout_common_title.layout_parent

/**
 *采购收料
 */
class CaiGouShouLiaoActivity : BaseClickActivity<CaiGouShouLiaoPresenter>(), ICaiGouShouLiaoView {
    private var mAdapter: CommonRecyclerViewAdapter<ServerBean.PurchasePOScanResponseTempModule>? =
        null
    private var mHasCommitFailed = false
    private val mUpdateDataList = mutableListOf<ServerBean.PurchasePOScanResponseTempModule>()
    override fun clickAction(view: View) {
        when (view.id) {
            //扫描
            R.id.tv_scan_content -> {
                startActivityForResult(Intent(this, ScanCodeActivity::class.java), scanCodeRequest)
            }
            //提交
            R.id.tv_commit -> {
                mHasCommitFailed = false
                mUpdateDataList.clear()
                for (position in mPresenter.mDataList.indices) {
                    val itemData = mPresenter.mDataList[position]
                    var originalData: ServerBean.PurchasePOScanResponseTempModule? = null
                    for (tempData in mPresenter.mScanResponse!!) {
                        if (itemData.id == tempData.id) {
                            originalData = tempData
                            break
                        }
                    }
                    if (originalData != null && (itemData.qty != originalData.qty || itemData.price != originalData.price)) {
                        mUpdateDataList.add(itemData)
                    }
                }
                if (mUpdateDataList.isEmpty()) {
                    mPresenter.commit()
                } else {
                    showLoadingDialog()
                    for (itemData in mUpdateDataList) {
                        mPresenter.updateTranPoTemp(
                            id = itemData.id,
                            qty = itemData.qty,
                            price = itemData.price
                        )
                    }
                }
            }
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_caigou_shouliao_layout
    }

    override fun initViews() {
        super.initViews()
        ImmersionBar.with(this).statusBarColor(R.color.main_color)
            .titleBarMarginTop(layout_parent)
            .init()
        setTitle(R.string.caigou_shouliao)
        mTitleBar.getTitleLayoutAll(this).setBackgroundColor(getColor(R.color.main_color))
        mTitleBar.setLeftImgTint(ColorStateList.valueOf(Color.WHITE))
        mTitleBar.setTitleColor(Color.WHITE)
        tv_scan_content?.setOnClickListener(this)
        tv_commit?.setOnClickListener(this)
        mAdapter = object : CommonRecyclerViewAdapter<ServerBean.PurchasePOScanResponseTempModule>
            (this, R.layout.item_caigou_shouliao_layout, mPresenter.mDataList) {
            @SuppressLint("SetTextI18n")
            override fun convert(
                holder: CommonRecyclerViewHolder?,
                bean: ServerBean.PurchasePOScanResponseTempModule?,
                position: Int
            ) {
                if (position % 2 == 0) {
                    holder?.convertView?.setBackgroundColor(getColor(R.color.color_DADADE))
                } else {
                    holder?.convertView?.setBackgroundColor(getColor(R.color.color_8FD3F3))
                }
                holder?.getView<TextView>(R.id.tv_line)?.text = (position + 1).toString()
                holder?.getView<TextView>(R.id.tv_chang_jia)?.text = bean?.vendName
                holder?.getView<TextView>(R.id.tv_cai_zhi)?.text = bean?.artId
                holder?.getView<TextView>(R.id.tv_po)?.text = bean?.specs
                holder?.getView<TextView>(R.id.tv_gong_dan)?.text = bean?.dePo
                val et_song_huoshu = holder?.getView<EditText>(R.id.et_song_huoshu)
                val et_dan_jia = holder?.getView<EditText>(R.id.et_dan_jia)
                et_song_huoshu?.setText(bean?.qty?.toString() ?: "0", TextView.BufferType.EDITABLE)
                et_dan_jia?.setText(
                    bean?.price?.toString() ?: "0",
                    TextView.BufferType.EDITABLE
                )
                et_song_huoshu?.addTextChangedListener(afterTextChanged = {
                    bean?.qty = DataUtil.toInt(et_song_huoshu.text.toString())
                })
                et_dan_jia?.addTextChangedListener(afterTextChanged = {
                    bean?.price = DataUtil.toFloat(et_dan_jia.text.toString())
                })
            }
        }
        val layoutManager = LinearLayoutManager(this)
        layoutManager.setReverseLayout(true)
        layoutManager.setStackFromEnd(true)
        recycler.layoutManager = layoutManager
        recycler.isSwipeItemMenuEnabled = true
        recycler.setSwipeMenuCreator { leftMenu, rightMenu, position ->
            val deleteItem = SwipeMenuItem(this)
            deleteItem.setWidth(resources.getDimensionPixelSize(R.dimen.sw_dp_50))
            deleteItem.setHeight(resources.getDimensionPixelSize(R.dimen.sw_dp_80))
            deleteItem.setText(R.string.delete)
            deleteItem.setTextColor(Color.WHITE)
            deleteItem.setBackgroundColor(Color.RED)
            deleteItem.setTextSize(12)
            rightMenu.addMenuItem(deleteItem)
        }
        recycler.setOnItemMenuClickListener { menuBridge, adapterPosition ->
            menuBridge.closeMenu()
            mPresenter.deleteTranTemp(adapterPosition, mPresenter.mDataList[adapterPosition].id)
        }
        recycler.setOnItemClickListener { view, position ->
            println("click position=$position")
        }
        recycler.adapter = mAdapter
        val inputMethod = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        mPresenter.queryTemp()
    }

    private fun getNormalPopupWindow(
        dataList: List<ServerBean.GXInfo>,
        callback: (index: Int) -> Unit
    ): PopupWindow {
        return DialogUtil.getNormalPop(this, dataList, callback)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == scanCodeRequest && resultCode == Activity.RESULT_OK) {
            val scanResult = data?.getStringExtra(ScanCodeActivity.KEY_DATA) ?: ""
            if (scanResult.isEmpty()) {
                tv_scan_content?.text = getString(R.string.scan_code)
            } else {
                tv_scan_content?.text = scanResult
                mPresenter.scan(
                    barcode = scanResult
                )
            }
        }
    }

    override fun notifyAdapter() {
        mAdapter?.notifyDataSetChanged()
        if (mPresenter.mDataList.isEmpty()) {
            tv_scan_content?.text = ""
        }
    }


    override fun commitSuccess() {
        showToast(R.string.commit_success)
        notifyAdapter()
    }

    override fun commitFailed(message: String?) {
        showToast(if (message.isNullOrEmpty()) getString(R.string.commit_failed) else message)
    }

    override fun scanFailed(message: String?) {
        showToast(if (message.isNullOrEmpty()) getString(R.string.scan_failed) else message)
        tv_scan_content?.text = getString(R.string.scan_code)
    }

    override fun deleteTempSuccess() {
        showToast(R.string.delete_success)
        mAdapter?.notifyDataSetChanged()
    }

    override fun deleteTempFailed(message: String?) {
        showToast(if (message.isNullOrEmpty()) getString(R.string.delete_failed) else message)
    }

    override fun modifyTempSuccess() {
        if (mUpdateDataList.isNotEmpty()) {
            mUpdateDataList.removeFirst()
        }
        if (mUpdateDataList.isEmpty()) {
            if (mHasCommitFailed) {
                showToast(R.string.modify_failed)
                return
            }
            mPresenter.commit()
        }
    }

    override fun modifyTempFailed(message: String?) {
        mHasCommitFailed = true
        if (mUpdateDataList.isNotEmpty()) {
            mUpdateDataList.removeFirst()
        }
        if (mUpdateDataList.isEmpty()) {
            showToast(if (message.isNullOrEmpty()) getString(R.string.modify_failed) else message)
        }
    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun dismissLoading() {
        dismissLoadingDialog(true)
    }

    companion object {
        const val scanCodeRequest = 100

        @JvmStatic
        fun startActivity(activity: Activity) {
            activity.startActivity(Intent(activity, CaiGouShouLiaoActivity::class.java))
        }
    }
}